"""
HiAgent API路由
"""
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, Query, Body
from pydantic import BaseModel

from src.llm.hiagent_app.services.app_service import AppService
from src.llm.hiagent_app.services.favorite_service import FavoriteService
from src.llm.hiagent_app.services.personal_agent_service import PersonalAgentService
from src.llm.hiagent_app.services.plugin_service import PluginService
from src.llm.hiagent_app.services.knowledge_service import KnowledgeService
from src.llm.hiagent_app.models.hiagent_models import (
    AppType, AgentMode, ListOption, ListAppCenterFilter, ListAppBriefsFilter
)

router = APIRouter(prefix="/hiagent", tags=["HiAgent"])

# 初始化服务
app_service = AppService()
favorite_service = FavoriteService()
personal_agent_service = PersonalAgentService()
plugin_service = PluginService()
knowledge_service = KnowledgeService()


# 请求模型
class ListAppCenterRequest(BaseModel):
    workspace_id: Optional[str] = None
    page: Optional[int] = 1
    page_size: Optional[int] = 20
    category_id: Optional[str] = None
    app_types: Optional[List[str]] = None
    keyword: Optional[str] = None
    is_published: Optional[bool] = None


class AddToFavoritesRequest(BaseModel):
    app_id: str
    workspace_id: Optional[str] = None


class CreatePersonalAgentRequest(BaseModel):
    name: str
    description: str
    app_type: str
    icon: Optional[str] = None
    background: Optional[str] = None
    image: Optional[str] = None
    workflow_ids: Optional[List[str]] = None
    workspace_id: Optional[str] = None


class UpdatePersonalAgentRequest(BaseModel):
    app_id: str
    name: Optional[str] = None
    description: Optional[str] = None
    icon: Optional[str] = None
    background: Optional[str] = None
    image: Optional[str] = None
    http_runnable: Optional[bool] = None
    api_runnable: Optional[bool] = None
    workflow_ids: Optional[List[str]] = None
    workspace_id: Optional[str] = None


class CreateKnowledgeBaseRequest(BaseModel):
    name: str
    description: str
    workspace_id: Optional[str] = None
    icon: Optional[str] = None


# 应用中心相关接口
@router.get("/app-center/categories")
async def list_app_center_categories(workspace_id: Optional[str] = Query(None)):
    """获取应用中心分类列表"""
    try:
        categories = app_service.list_app_center_categories(workspace_id)
        return {"success": True, "data": categories}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/app-center/list")
async def list_app_center(request: ListAppCenterRequest):
    """获取应用中心列表"""
    try:
        list_opt = ListOption(
            page=request.page,
            page_size=request.page_size
        )
        
        filter_opt = ListAppCenterFilter(
            category_id=request.category_id,
            app_types=[AppType(t) for t in request.app_types] if request.app_types else None,
            keyword=request.keyword,
            is_published=request.is_published
        )
        
        apps, total = app_service.list_app_center(list_opt, filter_opt, request.workspace_id)
        
        return {
            "success": True,
            "data": {
                "items": [app.__dict__ for app in apps],
                "total": total,
                "page": request.page,
                "page_size": request.page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/app-center/favorites")
async def list_favorite_app_center(
    workspace_id: Optional[str] = Query(None),
    last_favorite_id: Optional[str] = Query(None),
    page_size: int = Query(20),
    category_id: Optional[str] = Query(None),
    keyword: Optional[str] = Query(None)
):
    """获取应用中心收藏列表"""
    try:
        filter_opt = None
        if category_id or keyword:
            filter_opt = ListAppCenterFilter(
                category_id=category_id,
                keyword=keyword
            )
        
        apps, last_id, has_more = app_service.list_favorite_app_center(
            last_favorite_id, page_size, filter_opt, workspace_id
        )
        
        return {
            "success": True,
            "data": {
                "items": [app.__dict__ for app in apps],
                "last_favorite_id": last_id,
                "has_more": has_more
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/app-center/recently-used")
async def list_recently_used_app_center(
    workspace_id: Optional[str] = Query(None),
    page: int = Query(1),
    page_size: int = Query(20),
    category_id: Optional[str] = Query(None),
    keyword: Optional[str] = Query(None)
):
    """获取应用中心最近使用列表"""
    try:
        list_opt = ListOption(page=page, page_size=page_size)
        
        filter_opt = None
        if category_id or keyword:
            filter_opt = ListAppCenterFilter(
                category_id=category_id,
                keyword=keyword
            )
        
        apps, total = app_service.list_recently_used_app_center(list_opt, filter_opt, workspace_id)
        
        return {
            "success": True,
            "data": {
                "items": [app.__dict__ for app in apps],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/app-center/{app_id}")
async def get_app_center_detail(app_id: str, workspace_id: Optional[str] = Query(None)):
    """获取应用中心应用详情"""
    try:
        app = app_service.get_app_center_detail(app_id, workspace_id)
        if not app:
            raise HTTPException(status_code=404, detail="Application not found")
        
        return {"success": True, "data": app.__dict__}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 收藏功能接口
@router.post("/favorites/add")
async def add_to_favorites(request: AddToFavoritesRequest):
    """添加到收藏列表"""
    try:
        success = favorite_service.add_to_favorites(request.app_id, request.workspace_id)
        return {"success": success, "message": "Added to favorites" if success else "Failed to add to favorites"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/favorites/remove")
async def remove_from_favorites(request: AddToFavoritesRequest):
    """从收藏列表移除"""
    try:
        success = favorite_service.remove_from_favorites(request.app_id, request.workspace_id)
        return {"success": success, "message": "Removed from favorites" if success else "Failed to remove from favorites"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/favorites/homepage")
async def list_favorites_in_homepage(
    workspace_id: Optional[str] = Query(None),
    page: int = Query(1),
    page_size: int = Query(20)
):
    """获取首页右侧收藏列表"""
    try:
        list_opt = ListOption(page=page, page_size=page_size)
        apps = favorite_service.list_favorites_in_homepage(list_opt, None, workspace_id)
        
        return {
            "success": True,
            "data": {
                "items": [app.__dict__ for app in apps],
                "page": page,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 个人智能体管理接口
@router.get("/personal-agents")
async def list_personal_agents(
    workspace_id: Optional[str] = Query(None),
    page: int = Query(1),
    page_size: int = Query(20),
    keyword: Optional[str] = Query(None),
    app_type: Optional[str] = Query(None),
    is_published: Optional[bool] = Query(None)
):
    """获取个人智能体列表"""
    try:
        list_opt = ListOption(page=page, page_size=page_size)
        
        filter_opt = ListAppBriefsFilter(
            keyword=keyword,
            app_types=[AppType(app_type)] if app_type else None,
            is_published=is_published
        )
        
        apps, total = personal_agent_service.list_personal_agents(list_opt, filter_opt, workspace_id)
        
        return {
            "success": True,
            "data": {
                "items": [app.__dict__ for app in apps],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/personal-agents/{app_id}")
async def get_personal_agent(app_id: str, workspace_id: Optional[str] = Query(None)):
    """获取个人智能体详情"""
    try:
        app = personal_agent_service.get_personal_agent(app_id, workspace_id)
        if not app:
            raise HTTPException(status_code=404, detail="Personal agent not found")
        
        return {"success": True, "data": app.__dict__}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/personal-agents")
async def create_personal_agent(request: CreatePersonalAgentRequest):
    """创建个人智能体"""
    try:
        app_id = personal_agent_service.create_personal_agent(
            name=request.name,
            description=request.description,
            app_type=AppType(request.app_type),
            icon=request.icon,
            background=request.background,
            image=request.image,
            workflow_ids=request.workflow_ids,
            workspace_id=request.workspace_id
        )
        
        if not app_id:
            raise HTTPException(status_code=400, detail="Failed to create personal agent")
        
        return {"success": True, "data": {"app_id": app_id}}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/personal-agents")
async def update_personal_agent(request: UpdatePersonalAgentRequest):
    """更新个人智能体"""
    try:
        success = personal_agent_service.update_personal_agent(
            app_id=request.app_id,
            name=request.name,
            description=request.description,
            icon=request.icon,
            background=request.background,
            image=request.image,
            http_runnable=request.http_runnable,
            api_runnable=request.api_runnable,
            workflow_ids=request.workflow_ids,
            workspace_id=request.workspace_id
        )
        
        return {"success": success, "message": "Updated successfully" if success else "Failed to update"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/personal-agents/{app_id}")
async def delete_personal_agent(app_id: str, workspace_id: Optional[str] = Query(None)):
    """删除个人智能体"""
    try:
        success = personal_agent_service.delete_personal_agent(app_id, workspace_id)
        return {"success": success, "message": "Deleted successfully" if success else "Failed to delete"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 插件中心接口
@router.get("/plugins/categories")
async def list_plugin_categories(workspace_id: Optional[str] = Query(None)):
    """获取插件分类列表"""
    try:
        categories = plugin_service.list_available_plugin_categories(workspace_id)
        return {"success": True, "data": categories}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/plugins")
async def list_plugins(
    workspace_id: Optional[str] = Query(None),
    page: int = Query(1),
    page_size: int = Query(20),
    category_id: Optional[str] = Query(None),
    keyword: Optional[str] = Query(None),
    plugin_type: Optional[str] = Query(None),
    is_released: Optional[bool] = Query(None)
):
    """获取插件列表"""
    try:
        plugins, total = plugin_service.list_plugins(
            workspace_id, page, page_size, category_id, keyword, plugin_type, is_released
        )
        
        return {
            "success": True,
            "data": {
                "items": [plugin.__dict__ for plugin in plugins],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/plugins/released")
async def list_released_plugins(
    workspace_id: Optional[str] = Query(None),
    page: int = Query(1),
    page_size: int = Query(20),
    category_id: Optional[str] = Query(None),
    keyword: Optional[str] = Query(None)
):
    """获取已上架插件列表"""
    try:
        plugins, total = plugin_service.list_released_plugins(
            workspace_id, page, page_size, category_id, keyword
        )
        
        return {
            "success": True,
            "data": {
                "items": [plugin.__dict__ for plugin in plugins],
                "total": total,
                "page": page,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/plugins/{plugin_id}")
async def get_plugin_detail(plugin_id: str, workspace_id: Optional[str] = Query(None)):
    """获取插件详情"""
    try:
        plugin = plugin_service.get_plugin_detail(plugin_id, workspace_id)
        if not plugin:
            raise HTTPException(status_code=404, detail="Plugin not found")
        
        return {"success": True, "data": plugin.__dict__}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 知识库管理接口
@router.get("/knowledge-bases")
async def list_knowledge_bases(
    workspace_id: Optional[str] = Query(None),
    page_number: int = Query(1),
    page_size: int = Query(10),
    keyword: Optional[str] = Query(None)
):
    """获取知识库列表"""
    try:
        datasets, total = knowledge_service.list_datasets(
            workspace_id, page_number, page_size, keyword
        )
        
        return {
            "success": True,
            "data": {
                "items": [dataset.__dict__ for dataset in datasets],
                "total": total,
                "page_number": page_number,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/knowledge-bases/{dataset_id}")
async def get_knowledge_base(dataset_id: str, workspace_id: Optional[str] = Query(None)):
    """获取知识库详情"""
    try:
        dataset = knowledge_service.get_dataset(dataset_id, workspace_id)
        if not dataset:
            raise HTTPException(status_code=404, detail="Knowledge base not found")
        
        return {"success": True, "data": dataset.__dict__}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/knowledge-bases")
async def create_knowledge_base(request: CreateKnowledgeBaseRequest):
    """创建知识库"""
    try:
        dataset_id = knowledge_service.create_dataset(
            name=request.name,
            description=request.description,
            workspace_id=request.workspace_id,
            icon=request.icon
        )
        
        if not dataset_id:
            raise HTTPException(status_code=400, detail="Failed to create knowledge base")
        
        return {"success": True, "data": {"dataset_id": dataset_id}}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/knowledge-bases/{dataset_id}")
async def delete_knowledge_base(dataset_id: str, workspace_id: Optional[str] = Query(None)):
    """删除知识库"""
    try:
        success = knowledge_service.delete_dataset(dataset_id, workspace_id)
        return {"success": success, "message": "Deleted successfully" if success else "Failed to delete"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/knowledge-bases/{dataset_id}/documents")
async def list_documents(
    dataset_id: str,
    workspace_id: Optional[str] = Query(None),
    page_number: int = Query(1),
    page_size: int = Query(10),
    keyword: Optional[str] = Query(None)
):
    """获取知识库文档列表"""
    try:
        documents, total = knowledge_service.list_documents(
            dataset_id, workspace_id, page_number, page_size, keyword
        )
        
        return {
            "success": True,
            "data": {
                "items": documents,
                "total": total,
                "page_number": page_number,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/knowledge-bases/{dataset_id}/query")
async def query_knowledge_base(
    dataset_id: str,
    query: str = Body(..., embed=True),
    workspace_id: Optional[str] = Query(None),
    top_k: int = Query(5),
    score_threshold: Optional[float] = Query(None)
):
    """知识库检索"""
    try:
        results = knowledge_service.query_knowledge(
            dataset_id, query, workspace_id, top_k, score_threshold
        )
        
        return {"success": True, "data": results}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))